using System;
using CGF;
using UnityEngine;
using UnityEngine.UI;

public class Cart : MonoBehaviour
{
    public Vector2 offset = new Vector2(25, 0);
    public float xSpace = 90;
    public Text[] xTexts = new Text[7];
    public Text[] yTexts = new Text[4];
    public CLine line;
    public GameObject emptyTip;

    private Vector2 _offset = new Vector2(0, 0);
    private float _xSpace = 0;
    private float[] yValues;
    private Line l;

    private void Start()
    {
        _offset = offset;
        _xSpace = xSpace;
    }

    private void Update()
    {
        if (_offset != offset || _xSpace != xSpace)
        {
            _offset = offset;
            _xSpace = xSpace;
            DrawLine();
        }
    }

    public void SetData(string[] xNames, float yAxisMin, float yAxisMax, float[] yValues)
    {
        if (xNames != null)
        {
            for (int i = 0; i < xTexts.Length; i++)
            {
                xTexts[i].text = xNames.Length > i ? xNames[i] : "";
            }
        }
        else
        {
            for (int i = 0; i < xTexts.Length; i++)
            {
                xTexts[i].text = "";
            }
        }

        if (yValues != null && yValues.Length > 0)
        {
            this.yValues = yValues;
            float yMin = float.MaxValue;
            float yMax = float.MinValue;
            for (int i = 0; i < yValues.Length; i++)
            {
                if (yValues[i] < yMin)
                {
                    yMin = yValues[i];
                }
                if (yValues[i] > yMax)
                {
                    yMax = yValues[i];
                }
            }
            int ySub = Mathf.RoundToInt((yMax - yMin) / (yTexts.Length - 1));
            yTexts[0].text = yMin.ToString();
            for (int i = 1; i < yTexts.Length - 1; i++)
            {
                yTexts[i].text = (yMin + i * ySub).ToString();
            }
            yTexts[yTexts.Length - 1].text = yMax.ToString();

            line.Points = new Vector2[yValues.Length];
            float maxPosY = (yTexts[yTexts.Length - 1].transform.parent as RectTransform).anchoredPosition.y - (yTexts[0].transform.parent as RectTransform).anchoredPosition.y;
            l = new Line(yMin, 0, yMax, maxPosY);
            DrawLine();
        }
        else
        {
            for (int i = 0; i < yTexts.Length; i++)
            {
                yTexts[i].text = "0";
            }
        }
        line.gameObject.SetActive(yValues == null || yValues.Length == 0);
        emptyTip.SetActive((yValues == null || yValues.Length == 0));
    }

    private void DrawLine()
    {
        for (int i = 0; i < line.Points.Length; i++)
        {
            line.Points[i] = new Vector2(offset.x + i * xSpace, offset.y + l.k * yValues[i] + l.b);
        }
        line.ReDraw();
    }
}
